import { Injectable } from '@nestjs/common';
import { BlogEntity } from './entities/blog.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Search } from 'src/common/decorators/search.decorator';

import { CreateBlogDto } from './dto/create-blog.dto';
import { UpdateBlogDto } from './dto/update-blog.dto';
import { ListBlogReturn } from './dto/list-blog.dto';

@Injectable()
export class BlogService {
  constructor(
    @InjectRepository(BlogEntity)
    private readonly blogRepository: Repository<BlogEntity>,
  ) {}

  async create(createBlogDto: CreateBlogDto): Promise<CreateBlogDto> {
    createBlogDto.length = createBlogDto.content.length;
    let blogItem = this.blogRepository.create(createBlogDto);
    blogItem = await this.blogRepository.save(blogItem);
    return await this.findOne(blogItem.id);
  }

  async findAll({
    page,
    limit,
    pagesize,
    offset,
    order,
    where,
  }: Search): Promise<ListBlogReturn> {
    const [rows, total] = await this.blogRepository.findAndCount({
      where,
      order,
      take: limit,
      skip: offset,
      relations: ['user'],
      select: ['id', 'title', 'image', 'keyword', 'length', 'visited'],
    });

    return {
      total,
      rows,
      page,
      pagesize,
    };
  }

  async findOne(id: string): Promise<BlogEntity> {
    const blogItem = await this.blogRepository.findOne({
      relations: ['user'],
      where: { id },
      select: [
        'id',
        'title',
        'content',
        'image',
        'keyword',
        'length',
        'visited',
      ],
    });
    return blogItem;
  }

  async update(id: string, updateBlogDto: UpdateBlogDto): Promise<string> {
    await this.blogRepository.update(id, updateBlogDto);
    return 'success';
  }

  async remove(id: string): Promise<string> {
    await this.blogRepository.softDelete(id);
    return 'success';
  }
}
